package lwk.juc.notify;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:lwk
 * @create: 2022-08-11 20:28
 * @Description: JUC顺序唤醒
 *
 */
public class JUCNotifyDemo {

    public static void main(String[] args) {

        DataOp3 dataOp = new DataOp3();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataOp.printA();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataOp.printB();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataOp.printC();
            }
        },"C").start();

    }

}


class DataOp3 {

    private int number = 1;
    private final Lock lock = new ReentrantLock();

    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            // 不等于0的时候等待
            while (number!=1) {
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName()+"AAA==>"+number);
            number = 2;
            conditionB.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            // 不等于2等待
            while (number!=2) {
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName()+"BBB==>"+number);
            number = 3;
            conditionC.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            // 不等于3等待
            while (number!=3) {
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName()+"CCC==>"+number);
            number = 1;
            conditionA.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}